#include "application.h"
// #include "liveplatforms/douyin.h"
// #include "liveplatforms/kuaishou.h"
#include "usersettings.h"
#include "version.h"
#include <QDateTime>
#include <QDir>
#include <QNetworkProxyFactory>

#ifndef QT_DEBUG
#define ENABLE_LOGGING
#endif

#ifdef ENABLE_LOGGING
#include "libs/base/log/logger.h"

#if defined(Q_OS_WIN32) && defined(ENABLE_LOGGING) && !defined(QT_DEBUG)
#define ENABLE_CRASHRPT
#ifdef ENABLE_CRASHRPT
#include "crashrpthelper/crashrpthelper.h"
#include "globalsettings.h"
#endif
#endif

static yc::Logger* globalLogger = nullptr;
void loggerOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
    Q_UNUSED(context)
    if (type != QtDebugMsg && type != QtWarningMsg && type != QtFatalMsg && type != QtCriticalMsg) {
        return;
    }

    switch (type) {
    case QtDebugMsg:
        *globalLogger << "DEBUG ";
        break;
    case QtInfoMsg:
        *globalLogger << "INFO ";
        break;
    case QtWarningMsg:
        *globalLogger << "WARNING ";
        break;
    case QtCriticalMsg:
        *globalLogger << "CRITICAL ";
        break;
    case QtFatalMsg:
        *globalLogger << "FATAL ";
        break;
    default:
        *globalLogger << "LOG ";
        break;
    }
    *globalLogger << QDateTime::currentDateTime().toString("yyyy/MM/dd HH:mm:ss");
    *globalLogger << ":";
    *globalLogger << msg;
    *globalLogger << "\n";
}
#endif // ENABLE_LOGGING

static void setHighDpiEnvironmentVariable()
{
#ifndef Q_OS_MAC
    if (!qEnvironmentVariableIsSet("QT_DEVICE_PIXEL_RATIO") // legacy in 5.6, but still functional
        && !qEnvironmentVariableIsSet("QT_AUTO_SCREEN_SCALE_FACTOR")
        && !qEnvironmentVariableIsSet("QT_SCALE_FACTOR")
        && !qEnvironmentVariableIsSet("QT_SCREEN_SCALE_FACTORS")) {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#if QT_VERSION == QT_VERSION_CHECK(5, 14, 0)
        // work around QTBUG-80934
        QGuiApplication::setHighDpiScaleFactorRoundingPolicy(
                Qt::HighDpiScaleFactorRoundingPolicy::Round);
#endif

#endif
    } else {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
        /* AA_DisableHighDpiScaling is deprecated */
        QGuiApplication::setHighDpiScaleFactorRoundingPolicy(
                Qt::HighDpiScaleFactorRoundingPolicy::Floor);
#endif
    }
#endif
}

int main(int argc, char* argv[])
{
    QCoreApplication::setApplicationName("YingCe");
    QCoreApplication::setApplicationVersion(QLatin1String(YINGCE_VERSION_STR));
    QCoreApplication::setOrganizationDomain("com.yingce");
//    QGuiApplication::setApplicationDisplayName("YingCe");
#if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    if (!qEnvironmentVariableIsSet("QT_OPENGL")) {
        QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);
    }
#else
    // qputenv("QSG_RHI_BACKEND", "opengl");
    // QGuiApplication::setHighDpiScaleFactorRoundingPolicy(
    //         Qt::HighDpiScaleFactorRoundingPolicy::Round);
#endif
    setHighDpiEnvironmentVariable();

    // Application::setDesktopSettingsAware(false);
    Application app(argc, argv);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    app.setAttribute(Qt::AA_UseHighDpiPixmaps);
    // 去掉帮助按钮
    app.setAttribute(Qt::AA_DisableWindowContextHelpButton);
#endif
    //    app.setAttribute(Qt::AA_DontShowShortcutsInContextMenus, false);
    //    app.setAttribute(Qt::AA_DontShowIconsInMenus, true);
    app.setDesktopFileName("com.yingce.desktop");

    // Make sure we honor the system's proxy settings
    QNetworkProxyFactory::setUseSystemConfiguration(true);

    if (UserSettings::instance().webDebugEnabled()) {
        qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "12345");
    }

    // // 压缩Script Source Code
    // const auto code = DouYin::webEntry().script.source_code;
    // const auto ba = qCompress(code.toUtf8());
    // const auto ba2 = ba.toHex();
    // qDebug() << QString::fromLatin1(ba2);

#ifdef ENABLE_LOGGING
    {
        // init Logger
        QDir dir(UserSettings::logDir());
        yc::Logger::clearExpiredLogFiles(dir.absolutePath(), 5);
        QString base_name("yingce");
        QString ver(YINGCE_VERSION_STR);
        ver.replace(".", "");
        base_name += ver;
        const QString path = dir.absoluteFilePath(yc::Logger::getLogFileName(base_name));
        globalLogger = new yc::Logger(path, 2048);
        qInstallMessageHandler(loggerOutput);
#ifdef ENABLE_CRASHRPT
        const QString name = QString("YingCe");
        const QString version = GlobalSettings::currentVersion();
        CrashrptHelper::installCrashrpt(name.toStdWString().c_str(), version.toStdWString().c_str(),
                                        path.toStdWString().c_str());
#endif
    }
#endif

    int ret = app.exec();

#ifdef ENABLE_CRASHRPT
    CrashrptHelper::uninstallCrashrpt();
#endif
    return ret;
}
